package org.ai.demo.gateway.filter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

@Component
public class PostRequestFilter extends ZuulFilter {

	private static final Logger LOG = LoggerFactory.getLogger(PostRequestFilter.class);

	@Override
	public String filterType() {
		return "post";
	}

	@Override
	public int filterOrder() {
		return 12;// int值来定义过滤器的执行顺序，数值越小优先级越高
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException{
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		Throwable throwable = ctx.getThrowable();
		if(throwable != null) {
			System.out.println("error:" + throwable.getCause().getMessage());
		}

		HttpServletResponse response = ctx.getResponse();
		int status = response.getStatus();
		if(status == 401) {
            
		}
		
		String requestURI = request.getRequestURI();
		if (requestURI.endsWith("oauth/token") && status == 200) {
			System.out.println("RemoteAddr:" + request.getRemoteAddr());
			System.out.println("RemoteHost:" + request.getRemoteHost());
		}

//		System.out.println("Headers Start**********************");
//		Enumeration<String> headers = request.getHeaderNames();
//		while (headers.hasMoreElements()) {
//			String header = headers.nextElement();
//			String headerValue = request.getHeader(header);
//			System.out.println("Header:" + header + ", Value:" + headerValue);
//
//		}
//		System.out.println("Headers end**********************");

		String clientId = null;
		String clientSecret = null;
		Map<String, String[]> parameters = request.getParameterMap();
		String[] clients = parameters.get("client_id");
		String[] clientSecrets = parameters.get("client_secret");
		if (null != clients && clients.length > 0) {
			clientId = clients[0];
		}
		if (null != clientSecrets && clientSecrets.length > 0) {
			clientSecret = clientSecrets[0];
		}

		//异步保存到redis或数据库
		CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
	        
	    });
		try {
			future.get();
		} catch (Exception e) {
			LOG.error("执行失败！"+ e.getMessage());
		}
			
		
	    future.exceptionally(new Function<Throwable, Void>() {
	        @Override
	        public Void apply(Throwable t) {
	        	LOG.error("执行失败！"+t.getMessage());
	            return null;
	        }
	    });
		
		return null;
	}
	
}
